//
//  KINGNewFeatureController.swift
//  肉荣微博
//
//  Created by king on 15/7/31.
//  Copyright © 2015年 king. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class KINGNewFeatureController: UICollectionViewController {
    //新特性页面个数
    private let count = 4
    //设置布局方式
    private let layout = KINGNewFeatureFlowLayout()
    //构造方法，没有重写关键字，带有布局的方式的构造方法才是指定的构造函数
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Register cell classes
        self.collectionView!.registerClass(KINGNewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - 代理方法
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell:KINGNewFeatureCell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! KINGNewFeatureCell
        //cell.backgroundColor = UIColor.whiteColor()
        // Configure the cell
        cell.imageName = "new_feature_\(indexPath.item + 1)"
        
        return cell
    }
    
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        //indexPathsForVisibleItems 当前显示的item
        let currentIndexPath = collectionView.indexPathsForVisibleItems().last
        if currentIndexPath?.item == count - 1 {
            let cell = collectionView.cellForItemAtIndexPath(currentIndexPath!) as! KINGNewFeatureCell
            cell.startBtnAnimation()
        }
    }

    //MARK: - 隐藏状态栏
    override func prefersStatusBarHidden() -> Bool {
        return true
    }

}

class KINGNewFeatureCell: UICollectionViewCell {
    //代理属性
    var imageName: String? {
        didSet {
            iconView.image = UIImage(named: imageName!)
            startButton.hidden = true
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(iconView)
        contentView.addSubview(startButton)
        
        iconView.translatesAutoresizingMaskIntoConstraints = false
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[icon]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["icon": iconView]))
        addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[icon]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["icon": iconView]))
        
        startButton.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: startButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: -160))
    }
    
    func startBtnAnimation() {
        startButton.hidden = false
        startButton.userInteractionEnabled = false
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                self.startButton.transform = CGAffineTransformIdentity
            }) { (_) -> Void in
                self.startButton.userInteractionEnabled = true
        }
    }
    //点击事件
    func clickStartBtn() {
        NSNotificationCenter.defaultCenter().postNotificationName(KINGRootControllerSwitchNSNotification, object: true)
    }
    //懒加载一个控件
    private lazy var iconView: UIImageView = UIImageView()
    private lazy var startButton: UIButton = {
        let startBtn = UIButton()
        startBtn.setTitle("开始体验", forState: UIControlState.Normal)
        startBtn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        startBtn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        startBtn.addTarget(self, action: "clickStartBtn", forControlEvents: UIControlEvents.TouchUpInside)
        startBtn.sizeToFit()
        return startBtn
    }()
}
/// 每次在布局之前都会调用一次这个函数
class KINGNewFeatureFlowLayout: UICollectionViewFlowLayout {
    //每次准备布局之前，都会调用一次这个函数，如果布局没有改变，那么这个函数只执行一次
    override func prepareLayout() {
        //配置布局信息
        itemSize = collectionView!.bounds.size
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        minimumInteritemSpacing = 0.0
        minimumLineSpacing = 0.0
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        //没有间距
        collectionView?.bounces = false
    }
}